/**留言榜单相关 */
const router = require('koa-router')();
const DB = require('../db');

/**
 * 获取榜单数据
 */
router.get('/getLeaveMessageRank', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const r0 = await DB.findInSortAndLimit('leaveMessageRank', { $match: { hotNumber: { $gt: 0 } } }, { hotNumber: -1 }, 100);
  const r00 = r0.map((item, index) => Object.assign({}, item, { sort: index + 1 }));
  const mySort = r00.findIndex(item => item.userName === userName);
  const r1 = await DB.find('leaveMessageRank', { userName });
  if (r1.length > 0) {
    r1[0].sort = mySort + 1;
  }
  const r2 = await DB.find('users', { userName });
  ctx.body = {
    code: '0000',
    message: 'ok',
    data: {
      totalRank: r00,
      myRank: r1.length > 0 ? r1 : [{
        userName,
        avatarUrl: r2[0].avatarUrl
      }]
    }
  }
})

module.exports = router;